package com.hankol.material;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.baselibrary.MessageBus;
import com.baselibrary.activity.BaseActivity;
import com.baselibrary.bean.download.ShowUIUtils;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.net.APIResponse;
import com.baselibrary.permission.PermissionCollection;
import com.baselibrary.permission.PermissionsUtils;
import com.baselibrary.permission.callback.PermissionsCall;
import com.baselibrary.utils.DoubleClickHelper;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.HKToastUtils;
import com.baselibrary.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.transition.platform.MaterialContainerTransform;
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback;
import com.hankol.material.adapter.ImagePreviewAdapter;
import com.hankol.material.api.MaterialConstants;
import com.hankol.material.bean.CreateFolderBean;
import com.hankol.material.bean.FolderListBean;
import com.hankol.material.bean.MaterialContentInfo;
import com.hankol.material.bean.TabConfigure;
import com.hankol.material.view.ImageLoader;
import com.hankol.material.view.ImagePreview;
import com.hankol.material.viewmodel.MaterialBaseViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import cc.shinichi.library.bean.ImageInfo;
import cc.shinichi.library.glide.FileTarget;
import cc.shinichi.library.glide.progress.ProgressInterceptor;
import cc.shinichi.library.tool.common.HandlerUtils;
import cc.shinichi.library.view.HackyViewPager;

/**
 * 图片详情
 *
 * @email qinglingou@gmail.com
 */
public class ImagePreviewActivity extends BaseActivity implements Handler.Callback, View.OnClickListener {

    public static final String TAG = "ImagePreview";

    private Activity context;
    private HandlerUtils.HandlerHolder handlerHolder;

    private List<ImageInfo> imageInfoList;
    private int currentItem;
    private int lastItem;
    private boolean isShowOriginButton;

    private ImagePreviewAdapter imagePreviewAdapter;
    private HackyViewPager viewPager;

    private FrameLayout fm_center_progress_container;
    private TextView tvShowOrigin, tvShowOrigin1, mTvMove, tvDownload, tvDownloadLeft, tvShare, tvShareLeft, tvDel;
    private ImageView imgCloseButton, imgCollect2cancelLeft;
    private View progressParentLayout;
    private LinearLayout llBottomFromCollect, llBottomFromMaterial;

    private boolean isUserCustomProgressView = false;
    // 原图按钮显示状态
    private boolean originalStatus = false;

    private String currentItemOriginPathUrl = "";
    private int lastProgress = 0;
    private MaterialBaseViewModel mViewModel;
    private List<MaterialContentInfo.FileLibsBean.DataBean> beanList;
    private SensorsDataManager mSensorsDataManager;

    public static void activityStart(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            // 过度动画效果只对安卓 5.0 以上有效
            View transitionView = ImagePreview.getInstance().getTransitionView();
            String transitionShareElementName = ImagePreview.getInstance().getTransitionShareElementName();
            // 如果未设置则使用默认动画
            if (transitionView != null && transitionShareElementName != null) {
                ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                        (Activity) context,
                        transitionView,
                        transitionShareElementName
                );
                context.startActivity(intent, options.toBundle());
            } else {
                context.startActivity(intent);
                if (context instanceof Activity) {
                    ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
            }
        } else {
            // 低于 5.0 使用默认动画
            context.startActivity(intent);
            if (context instanceof Activity) {
                ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        // 只有安卓版本大于 5.0 才可使用过度动画
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !TextUtils.isEmpty(ImagePreview.getInstance().getTransitionShareElementName())) {
            getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
            findViewById(android.R.id.content).setTransitionName("shared_element_container");
            setEnterSharedElementCallback(new MaterialContainerTransformSharedElementCallback());
            getWindow().setSharedElementEnterTransition(new MaterialContainerTransform().addTarget(android.R.id.content).setDuration(300L));
            getWindow().setSharedElementReturnTransition(new MaterialContainerTransform().addTarget(android.R.id.content).setDuration(250L));
        }
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_img_detail;
    }

    @Override
    protected void init() {
        mSensorsDataManager = SensorsDataManager.Companion.getInstance();
        mSensorsDataManager.onCreateTime();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        context = this;
        handlerHolder = new HandlerUtils.HandlerHolder(this);
        imageInfoList = ImagePreview.getInstance().getImageInfoList();
        if (null == imageInfoList || imageInfoList.size() == 0) {
            onBackPressed();
            return;
        }

        mViewModel = getActivityViewModelProvider(this).get(MaterialBaseViewModel.class);

        currentItem = ImagePreview.getInstance().getIndex();
        lastItem = currentItem;
        currentItemOriginPathUrl = imageInfoList.get(currentItem).getOriginUrl();
        isShowOriginButton = ImagePreview.getInstance().isShowOriginButton(currentItem);
        if (isShowOriginButton) {
            // 检查缓存是否存在
            checkCache(currentItemOriginPathUrl);
        }
        viewPager = findViewById(R.id.viewPager);
        fm_center_progress_container = findViewById(R.id.fm_center_progress_container);
        tvShowOrigin = findViewById(R.id.tv_show_origin);
        tvShowOrigin1 = findViewById(R.id.tv_see_origin);
        imgCollect2cancelLeft = findViewById(R.id.img_collect2cancel_left);
        mTvMove = findViewById(R.id.tv_move);
        tvDownload = findViewById(R.id.tv_download);
        tvDownloadLeft = findViewById(R.id.tv_download_left);
        tvShare = findViewById(R.id.tv_share);
        tvDel = findViewById(R.id.tv_del);
        tvShareLeft = findViewById(R.id.tv_share_left);
        tvShowOrigin1.setVisibility(View.GONE);
        tvShowOrigin.setVisibility(View.GONE);
        fm_center_progress_container.setVisibility(View.GONE);
        int progressLayoutId = ImagePreview.getInstance().getProgressLayoutId();
        // != -1 即用户自定义了view
        if (progressLayoutId != -1) {
            // add用户自定义的view到frameLayout中，回调进度和view
            progressParentLayout = View.inflate(context, ImagePreview.getInstance().getProgressLayoutId(), null);
            if (progressParentLayout != null) {
                fm_center_progress_container.removeAllViews();
                fm_center_progress_container.addView(progressParentLayout);
                isUserCustomProgressView = true;
            } else {
                // 使用默认的textView进行百分比的显示
                isUserCustomProgressView = false;
            }
        } else {
            // 使用默认的textView进行百分比的显示
            isUserCustomProgressView = false;
        }
        beanList = ImagePreview.getInstance().getBeanList();
        //来自收藏夹
        llBottomFromCollect = findViewById(R.id.ll_from_collect);
        //来自素材库
        llBottomFromMaterial = findViewById(R.id.ll_from_material);
        llBottomFromCollect.setVisibility(beanList.get(currentItem).isFromCollect() ? View.VISIBLE : View.GONE);
        llBottomFromMaterial.setVisibility(!beanList.get(currentItem).isFromCollect() ? View.VISIBLE : View.GONE);
        imgCollect2cancelLeft.setSelected(beanList.get(currentItem).isHasCollect() == 1);
        imgCloseButton = findViewById(R.id.imgCloseButton);
        ((TextView) findViewById(R.id.tv_title)).setText(beanList.get(currentItem).getName() + "." + beanList.get(currentItem).getDesc());
        imgCloseButton.setImageResource(ImagePreview.getInstance().getCloseIconResId());
        // 关闭页面按钮
        imgCloseButton.setOnClickListener(this);
        // 查看与原图按钮
        tvShowOrigin.setOnClickListener(this);
        tvShowOrigin1.setOnClickListener(this);
        //分享
        tvShare.setOnClickListener(this);
        tvDel.setOnClickListener(this);
        tvShareLeft.setOnClickListener(this);
        //下载
        tvDownload.setOnClickListener(this);
        tvDownloadLeft.setOnClickListener(this);
        mTvMove.setOnClickListener(this);
        imgCollect2cancelLeft.setOnClickListener(this);
        findViewById(R.id.ll_collect).setOnClickListener(this);

        imagePreviewAdapter = new ImagePreviewAdapter(this, imageInfoList);
        viewPager.setAdapter(imagePreviewAdapter);
        viewPager.setCurrentItem(currentItem);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (lastItem != position) {
                    //上报上一张的浏览时长
                    mSensorsDataManager.materialLook(beanList.get(currentItem).getName(),
                            MaterialConstants.MATERIAL_IMG, mSensorsDataManager.getBrowseTime());
                    mSensorsDataManager.onCreateTime();//开始新一张图片的计时
                    lastItem = position;
                }
                isShowTip = false;
                currentItem = position;
                if (ImagePreview.getInstance().getBigImagePageChangeListener() != null) {
                    ImagePreview.getInstance().getBigImagePageChangeListener().onPageSelected(position);
                }
                ((TextView) findViewById(R.id.tv_title)).setText(beanList.get(currentItem).getName() + "." + beanList.get(currentItem).getDesc());
                mViewModel.reqAddShareCount(beanList.get(currentItem).getId(), 2);
                //查看原图
                showOriginOption();
                currentItemOriginPathUrl = imageInfoList.get(position).getOriginUrl();

                isShowOriginButton = ImagePreview.getInstance().isShowOriginButton(currentItem);
                if (isShowOriginButton) {
                    // 检查缓存是否存在
                    checkCache(currentItemOriginPathUrl);
                } else {
                    gone();
                }
                // 如果是自定义百分比进度view，每次切换都先隐藏，并重置百分比
                if (isUserCustomProgressView) {
                    fm_center_progress_container.setVisibility(View.GONE);
                    lastProgress = 0;
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (ImagePreview.getInstance().getBigImagePageChangeListener() != null) {
                    ImagePreview.getInstance()
                            .getBigImagePageChangeListener()
                            .onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (ImagePreview.getInstance().getBigImagePageChangeListener() != null) {
                    ImagePreview.getInstance().getBigImagePageChangeListener().onPageScrollStateChanged(state);
                }
            }
        });
        showOriginOption();
        mViewModel.reqAddShareCount(beanList.get(currentItem).getId(), 2);
    }

    private void showOriginOption() {
        tvShowOrigin.setText("查看原图 " + ShowUIUtils.byteToString(beanList.get(currentItem).getFileSize()));
        tvShowOrigin1.setText("查看原图 " + ShowUIUtils.byteToString(beanList.get(currentItem).getFileSize()));
    }

    @Override
    public void onBackPressed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            supportFinishAfterTransition();
        } else {
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

        ImagePreview.getInstance().reset();
        if (imagePreviewAdapter != null) {
            imagePreviewAdapter.closePage();
        }
    }

    public int convertPercentToBlackAlphaColor(float percent) {
        percent = Math.min(1, Math.max(0, percent));
        int intAlpha = (int) (percent * 255);
        String stringAlpha = Integer.toHexString(intAlpha).toLowerCase();
        String color = "#" + (stringAlpha.length() < 2 ? "0" : "") + stringAlpha + "000000";
        return Color.parseColor(color);
    }

    public void setAlpha(float alpha) {
        int colorId = convertPercentToBlackAlphaColor(alpha);
        if (alpha >= 1) {
            if (originalStatus) {
                tvShowOrigin.setVisibility(View.VISIBLE);
                tvShowOrigin1.setVisibility(View.VISIBLE);
            }
        } else {
            tvShowOrigin.setVisibility(View.GONE);
            tvShowOrigin1.setVisibility(View.GONE);
            imgCloseButton.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == 0) {
            // 点击查看原图按钮，开始加载原图
            final String path = imageInfoList.get(currentItem).getOriginUrl();
            visible();
            if (isUserCustomProgressView) {
                gone();
            } else {
                tvShowOrigin.setText("0 %");
                tvShowOrigin1.setText("0 %");
            }
            if (checkCache(path)) {
                Message message = handlerHolder.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putString("url", path);
                message.what = 1;
                message.obj = bundle;
                handlerHolder.sendMessage(message);
                return true;
            }
            loadOriginImage(path);
        } else if (msg.what == 1) {
            // 加载完成
            Bundle bundle = (Bundle) msg.obj;
            String url = bundle.getString("url");
            gone();
            if (currentItem == getRealIndexWithPath(url)) {
                if (isUserCustomProgressView) {
                    fm_center_progress_container.setVisibility(View.GONE);
                    if (ImagePreview.getInstance().getOnOriginProgressListener() != null) {
                        progressParentLayout.setVisibility(View.GONE);
                        ImagePreview.getInstance().getOnOriginProgressListener().finish(progressParentLayout);
                    }
                    imagePreviewAdapter.loadOrigin(imageInfoList.get(currentItem));
                } else {
                    imagePreviewAdapter.loadOrigin(imageInfoList.get(currentItem));
                }
            }
        } else if (msg.what == 2) {
            // 加载中
            Bundle bundle = (Bundle) msg.obj;
            String url = bundle.getString("url");
            int progress = bundle.getInt("progress");
            if (currentItem == getRealIndexWithPath(url)) {
                if (isUserCustomProgressView) {
                    gone();
                    fm_center_progress_container.setVisibility(View.VISIBLE);
                    if (ImagePreview.getInstance().getOnOriginProgressListener() != null) {
                        progressParentLayout.setVisibility(View.VISIBLE);
                        ImagePreview.getInstance()
                                .getOnOriginProgressListener()
                                .progress(progressParentLayout, progress);
                    }
                } else {
                    visible();
                    tvShowOrigin.setText(String.format("%s %%", progress));
                    tvShowOrigin1.setText(String.format("%s %%", progress));
                }
            }
        } else if (msg.what == 3) {
            // 隐藏查看原图按钮
            tvShowOrigin.setVisibility(View.GONE);
            tvShowOrigin1.setVisibility(View.GONE);
            if (isShowTip) {
                ToastUtils.showShort(this, "已加载原图");
            }
            originalStatus = false;
        } else if (msg.what == 4) {
            // 显示查看原图按钮
            tvShowOrigin.setVisibility(View.VISIBLE);
            tvShowOrigin1.setVisibility(View.VISIBLE);
            originalStatus = true;
        }
        return true;
    }

    private int getRealIndexWithPath(String path) {
        for (int i = 0; i < imageInfoList.size(); i++) {
            if (path.equalsIgnoreCase(imageInfoList.get(i).getOriginUrl())) {
                return i;
            }
        }
        return 0;
    }

    private boolean checkCache(String url) {
        File cacheFile = ImageLoader.getGlideCacheFile(context, url);
        if (cacheFile != null && cacheFile.exists()) {
            gone();
            return true;
        } else {
            visible();
            return false;
        }
    }

    //是否 有提示“已加载原图”
    private boolean isShowTip = false;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        MaterialContentInfo.FileLibsBean.DataBean bean = beanList.get(currentItem);
        if (i == R.id.tv_show_origin || i == R.id.tv_see_origin) {
            isShowTip = true;
            handlerHolder.sendEmptyMessage(0);
        } else if (i == R.id.imgCloseButton) {
            onBackPressed();
        } else if (i == R.id.tv_download || i == R.id.tv_download_left) {
            if (DoubleClickHelper.isOnDoubleClick()) {
                HKToastUtils.showToast("请勿频繁操作");
                return;
            }
            PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.FILE.getPermissionList(), new PermissionsCall() {
                @Override
                public void permissionsPass() {
                    //点击下载
                    mViewModel.reqMaterialAuthenticity(bean.getId(), new APIResponse<Boolean>(this) {

                        @Override
                        public void onSuccess(Boolean result, String json) {
                            mViewModel.reqAddShareCount(bean.getId(), 0);
                            MaterialConstants.downloadFile(ImagePreviewActivity.this, currentItemOriginPathUrl, bean.getName() + "." + bean.getDesc(), bean.getThumbnail(), bean.getFileSize(), bean.getType());
                        }
                    });
                }
            });

        } else if (i == R.id.tv_share || i == R.id.tv_share_left) {
            if (DoubleClickHelper.isOnDoubleClick()) {
                HKToastUtils.showToast("请勿频繁操作");
                return;
            }
            // 点击分享
            mViewModel.shareMaterial(this, bean.getId(), bean.getName(), bean.getThumbnail(), true, TabConfigure.IMG.getTabConfig());
        } else if (i == R.id.tv_move) {
            if (DoubleClickHelper.isOnDoubleClick()) {
                HKToastUtils.showToast("请勿频繁操作");
                return;
            }
            //点击移动
            mViewModel.moveMaterial(this, this, bean.getId(), bean.getCollectionFolderId(), new APIResponse<Boolean>(this) {

                @Override
                public void onSuccess(Boolean result, String json) {
                    ToastUtils.showShort(context, "移动成功");
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.IMG.getTabConfig());
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.IMG.getTabConfig());
                    finish();
                }

                @Override
                protected void onFailed(String message) {
//                    super.onFailed(message);
                    ToastUtils.showShort(context, "网络异常，移动失败");
                }
            });
        } else if (i == R.id.img_collect2cancel_left || i == R.id.ll_collect) {
            if (DoubleClickHelper.isOnDoubleClick()) {
                HKToastUtils.showToast("请勿频繁操作");
                return;
            }
            //收藏 取消收藏
            if (bean.isHasCollect() == 1) {
                //已收藏--->取消收藏
                cancelCollect(false);
            } else {
                //未收藏--->收藏
                mViewModel.collectionMaterial(this, this, bean.getId(), new APIResponse<CreateFolderBean>(this) {

                    @Override
                    public void onSuccess(CreateFolderBean result, String json) {
                        bean.setHasCollect(1);
                        ToastUtils.showShort(context, "收藏成功");
                        imgCollect2cancelLeft.setSelected(true);
                        mSensorsDataManager.materialCollection(bean.getName(), MaterialConstants.MATERIAL_IMG);
                    }

                    @Override
                    protected void onFailed(String message) {
//                        super.onFailed(message);
                        ToastUtils.showShort(context, "网络异常，收藏失败");
                    }
                });
            }
        } else if (i == R.id.tv_del) {
            if (DoubleClickHelper.isOnDoubleClick()) {
                HKToastUtils.showToast("请勿频繁操作");
                return;
            }
            //删除
            cancelCollect(true);
        }
    }

    private void cancelCollect(Boolean isDel) {
        MaterialContentInfo.FileLibsBean.DataBean bean = beanList.get(currentItem);
        mViewModel.loadCancelCollection(bean.getCollectionFolderId(), bean.getId(), new APIResponse<Boolean>(this) {

            @Override
            public void onSuccess(Boolean result, String json) {
                bean.setHasCollect(0);
                if (bean.isFromCollect()) {
                    ToastUtils.showShort(context, "删除成功");
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.IMG.getTabConfig());
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.IMG.getTabConfig());
                } else {
                    ToastUtils.showShort(context, "已取消收藏");
                }
                imgCollect2cancelLeft.setSelected(false);
                if (isDel) {
                    finish();
                }
            }

            @Override
            protected void onFailed(String message) {
//                        super.onFailed(message);
                ToastUtils.showShort(context, "网络异常，删除失败");
            }
        });
    }

    private void gone() {
        handlerHolder.sendEmptyMessage(3);
    }

    private void visible() {
        handlerHolder.sendEmptyMessage(4);
    }

    private void loadOriginImage(final String path) {


        Glide.with(context)
                .downloadOnly()
                .load(path)
                .into(new FileTarget() {
                    @Override
                    public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                        super.onResourceReady(resource, transition);

                        Message message = handlerHolder.obtainMessage();
                        Bundle bundle = new Bundle();
                        bundle.putString("url", path);
                        message.what = 1;
                        message.obj = bundle;
                        handlerHolder.sendMessage(message);
                        ProgressInterceptor.removeListener(path);
                    }
                });
        ProgressInterceptor.addListener(path, progress -> {
            if (progress == lastProgress) {
                return;
            }
            lastProgress = progress;
            Message message = handlerHolder.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("url", path);
            bundle.putInt("progress", progress);
            message.what = 2;
            message.obj = bundle;
            handlerHolder.sendMessage(message);
        });
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(final MessageBus messageBus) {
        if (messageBus.getCodeType().equals(MessageBus.msgId_material_createFolder)) {
            if (mViewModel.getCreateFolderListener() != null) {
                mViewModel.getCreateFolderListener().onCreateFolder(((FolderListBean) messageBus.getParam1()));
            }
        }
    }

    @Override
    protected void onDestroy() {
        if(beanList.size()>=currentItem) {
            mSensorsDataManager.materialLook(beanList.get(currentItem).getName(), MaterialConstants.MATERIAL_IMG, mSensorsDataManager.getBrowseTime());
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}